//      OptimusEnzyme.c
//      
//      Copyright 2012 Dylan Storey <dstorey@dstorey-lab>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//      
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.

#include <stdio.h>
#include <zlib.h>	
#include "kseq.h"
#include "pcre.h"
#include "OptimusEnzyme.h"
#include "Digestor.c"


KSEQ_INIT(gzFile, gzread)

int main(int argc, char *argv[])
{
	if (argc == 1) {
		fprintf(stderr, "Usage: %s <proteinlibrary.fasta> <missed cleavages>\n", argv[0]);
		return 1;
	}

	// initialize variables for getting data into memory//
	gzFile fp;
	kseq_t *seq;
	int l;
	int current_record_index = 0;
	int num_records_allocated = 0;
	// open file //
	fp = gzopen(argv[1] , "r");
	seq = kseq_init(fp);
	
	PROTEINRECORD *library = NULL;
	while ((l = kseq_read(seq)) >= 0) { // while we have a record to read
 		PROTEINRECORD temp; // temporary variable of type PROTEINRECORD
		temp.name = malloc((strlen(seq->name.s) + 1) * sizeof(char));// allocate memory //
		temp.sequence = malloc((strlen(seq->seq.s)+1)* sizeof(char)); // allocate memory //
		strncpy(temp.name, seq->name.s, strlen(seq->name.s) + 1); // copy into memory //
		strncpy(temp.sequence,seq->seq.s,strlen(seq->seq.s)+1); // copy into memory //
		
		if (current_record_index == num_records_allocated){
			if(num_records_allocated == 0){
				num_records_allocated = 30000;
				}
			else{
				num_records_allocated += 10000;
				}
			void *_tmp = realloc(library, (num_records_allocated * sizeof(PROTEINRECORD)));
			if (!_tmp){ 
				fprintf(stderr, "ERROR: Couldn't realloc memory!\n");
				return(-1); 
				}
			library = (PROTEINRECORD*)_tmp;	
			}
		library[current_record_index] = temp; 
		current_record_index++;
		
		}	
// destroy our seq object
kseq_destroy(seq);
// close our file //
gzclose(fp);	
// Do work son!//
PEPTIDERECORD* argc_digested_library = argc_digest(library , atoi(argv[2]), current_record_index);

// cleaning up everything //
int i;
for (i = 0; i < current_record_index; i++){
	free(library[i].name);
	free(library[i].sequence);
	}
free(library);
	
return 0;
}



